import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { WarpperService } from '../../shared/service/Warpper.service';
import { FunctionService } from '../../shared/service/function.service';
import { UserService } from '../../shared/service/user.service';
import { LoginService } from '../../shared/service/login.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

  // 当前登陆用户
  user: any;

  private event: any;

  whyClass: String = '';
  whyClassArray: any[] = [];

  loading: Boolean = false;

  constructor(
    private router: Router,
    private functionService: FunctionService,
    private userService: UserService,
    private warpperService: WarpperService,
    private loginService: LoginService
  ) {
    // 从登录服务中获取用户
    this.user = this.loginService.user;

    this.event = {
      date: new Date(),
      cid: '',
      class: '',
      content: '',
      price: ''
    };
  }

  ngOnInit() {
    if (this.user) {
      // 获取分类数据
      this.getClass();
    }
  }

  /*****
  *  获取分类
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  getClass() {
    this.userService.getClassAll()
        .then((res) => {
          this.whyClassArray = this.functionService.clearObjToArray(res);
        });
  }

  /*****
  *  class change
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  classChange(e) {
    this.event['cid'] = e.id;
    this.event['class'] = e.name;
  }

  /*****
  *  保存事件 
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  saveEvent() {
    // 开启loading
    this.loading = true;

    const evt = {
      cid: this.event.cid,
      class: this.event.class,
      content: this.event.content,
      price: this.event.price,
      year: this.event.date.getFullYear(),
      month: this.event.date.getMonth() + 1,
      date: this.event.date.getDate(),
      hours: this.event.date.getHours(),
      minu: this.event.date.getMinutes(),
      secod: this.event.date.getSeconds()
    };

    const that = this;

    this.warpperService.setEventData(evt)
      .then((call) => {
          if (call === 200) {
            // 关闭,没跑这就是报错
            that.loading = false;
            // 清空输入
            that.event = {
              date: new Date(),
              content: '',
              price: ''
            };
            that.router.navigate(['/loading']);
          }
        });
  }

}
